package com.daffodil.workable.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.daffodil.core.dao.JpaDao;
import com.daffodil.util.StringUtils;
import com.daffodil.workable.controller.model.WorkableJsPlumbData;
import com.daffodil.workable.entity.WorkableLine;
import com.daffodil.workable.entity.WorkableNode;
import com.daffodil.workable.service.IWorkableJsPlumbDataService;
import com.daffodil.workable.service.IWorkableLineService;
import com.daffodil.workable.service.IWorkableNodeService;

/**
 * 
 * @author yweijian
 * @date 2022年4月7日
 * @version 1.0
 * @description
 */
@Service
public class WorkableJsPlumbDataServiceImpl implements IWorkableJsPlumbDataService{

    @Autowired
    private JpaDao<String> jpaDao;
    
    @Autowired
    private IWorkableNodeService workableNodeService;

    @Autowired
    private IWorkableLineService workableLineService;

    @Override
    @Transactional
    public void saveWorkableJsPlumbData(WorkableJsPlumbData jsPlumbData) {
        if(StringUtils.isNull(jsPlumbData)) {
            return;
        }
        this.saveWorkableNode(jsPlumbData.getNodeList());
        this.saveWorkableLine(jsPlumbData.getLineList());
    }
    
    /**
     * 保存任务节点
     * @param nodes
     */
    private void saveWorkableNode(List<WorkableNode> nodes) {
        if(StringUtils.isEmpty(nodes)) {
            return;
        }
        nodes.stream().forEach(node -> {
            if(StringUtils.isEmpty(node.getId())) {
                workableNodeService.insertWorkableNode(node);
            }else {
                workableNodeService.updateWorkableNode(node);
            }
        });
    }
    
    /**
     * 保存节点连线
     * @param lines
     */
    private void saveWorkableLine(List<WorkableLine> lines) {
        if(StringUtils.isEmpty(lines)) {
            return;
        }
        lines.stream().forEach(line -> {
            if(StringUtils.isEmpty(line.getId())) {
                workableLineService.insertWorkableLine(line);
            }else {
                workableLineService.updateWorkableLine(line);
            }
        });
    }

    @Override
    public WorkableJsPlumbData selectWorkableJsPlumbDataByTaskId(String taskId) {
        if(StringUtils.isEmpty(taskId)) {
            return null;
        }
        List<WorkableNode> nodeList = jpaDao.search("from WorkableNode where taskId = ?", taskId, WorkableNode.class);
        List<WorkableLine> lineList = jpaDao.search("from WorkableLine where taskId = ?", taskId, WorkableLine.class);
        WorkableJsPlumbData data = new WorkableJsPlumbData();
        data.setNodeList(nodeList);
        data.setLineList(lineList);
        return data;
    }

}
